/*
* Copyright 2016 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-wechat
*
* @File name : DealerWechatMessageService.java
*
* @Author : LiuJun
*
* @Date : 2016年12月6日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2016年12月6日    LiuJun    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.wechatpush.service;

import static org.marketing.common.constants.MessagePushConstant.WX_MSG_PROP_COLOR;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.constants.BusinessConstant;
import org.marketing.common.constants.MessagePushConstant;
import org.marketing.common.dto.dealerInfo.NewsActivityDto;
import org.marketing.common.entity.Check;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocol;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocolMessageContent;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocolMessageTemplateContent;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocolReceiver;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocolSender;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventWechatAttentionDTO;
import org.marketing.common.event.EventWechatUnAttentionDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CookieSecurityUtil;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.wechatpush.common.ApiVersionConsts;
import com.yonyou.gmmc.service.wechatpush.common.HttpClientUtil;
import com.yonyou.gmmc.service.wechatpush.common.WechatDict;
import com.yonyou.gmmc.service.wechatpush.dao.TmPotentialUserMapper;
import com.yonyou.gmmc.service.wechatpush.dao.TmReplyKeywordMapper;
import com.yonyou.gmmc.service.wechatpush.dao.TmReplySmartMapper;
import com.yonyou.gmmc.service.wechatpush.dao.TtMessageMapper;
import com.yonyou.gmmc.service.wechatpush.dao.TtReplyTempMapper;
import com.yonyou.gmmc.service.wechatpush.dao.TtUserProblemMapper;
import com.yonyou.gmmc.service.wechatpush.dto.WxGzMessageDto;
import com.yonyou.gmmc.service.wechatpush.entity.Result;
import com.yonyou.gmmc.service.wechatpush.model.TmPotentialUser;
import com.yonyou.gmmc.service.wechatpush.model.TmReplyKeyword;
import com.yonyou.gmmc.service.wechatpush.model.TmReplySmart;
import com.yonyou.gmmc.service.wechatpush.model.TtReplyTemp;
import com.yonyou.gmmc.service.wechatpush.model.TtUserProblem;
import com.yonyou.gmmc.service.wechatpush.util.EncoderHandler;
import com.yonyou.gmmc.service.wechatpush.util.HttpsUtil;
import com.yonyou.gmmc.service.wechatpush.util.WechatMessageHandleUtils;
import com.yonyou.gmmc.servicee.wechatpush.encryption.WXBizMsgCrypt;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.mapper.entity.Example;

/**
 * @author LiuJun 接收经销商服务号消息service
 * @date 2016年12月6日
 */
@Service
public class WechatMessageService {

	private Logger logger = Logger.getLogger(WechatMessageService.class);

	@Autowired
	private BaseService eventService;
	@Autowired
	private TokenService tokenService;

	@Autowired
	private TmPotentialUserMapper tmPotentialUserMapper;

	@Autowired
	private TmReplyKeywordMapper tmReplyKeywordMapper;

	@Autowired
	private TmReplySmartMapper tmReplySmartMapper;

	@Autowired
	private TtReplyTempMapper ttReplyTempMapper;

	@Autowired
	private TtUserProblemMapper ttUserProblemMapper;

	@Autowired
	private TtMessageMapper ttMessageMapper;

	@Autowired
	private ChatServiceInterface chatServiceInterface;

	@Value("${KEY_WORD}")
	private String keyWord;

	public String validate(String wxToken, Check tokenModel) {
		String signature = tokenModel.getSignature();
		Long timestamp = tokenModel.getTimestamp();
		Long nonce = tokenModel.getNonce();
		String echostr = tokenModel.getEchostr();
		if (signature != null && timestamp != null && nonce != null) {
			String[] str = { wxToken, timestamp + "", nonce + "" };
			Arrays.sort(str); // 字典序排序
			String bigStr = str[0] + str[1] + str[2];
			// SHA1加密
			String digest = EncoderHandler.encode("SHA1", bigStr).toLowerCase();
			// 确认请求来至微信
			if (digest.equals(signature)) {
				return echostr;
			}
		}
		return "error";
	}

	/**
	 * @author LiuJun 接收并回复微信第三方平台消息
	 * @date 2016年12月6日
	 * @param dealerAppid
	 * @param nonce
	 * @param timestamp
	 * @param signature
	 * @param xml
	 * @return
	 * @throws ServiceBizException
	 */
	public String receiveAndReplyDealerWeChatMsg(
			String xml, HttpServletResponse response, HttpServletRequest request)
			throws ServiceBizException {
		try {
			// WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token,
			// WechatDict.AESKey, WechatDict.appid);
			// String parsedXml = crypt.decryptMsg(signature, timestamp, nonce,
			// xml);
			Map<String, String> xmlMap = WechatMessageHandleUtils.xmlToMap(xml);// parsedXml
			String openId = request.getHeader(ApiVersionConsts.HEADER_OPENID);
			String msgType = xmlMap.get("MsgType");
			String content = xmlMap.get("Content");
			String msgId = xmlMap.get("MsgId");
			if (WechatDict.MESSAGE_TYPE_TEXT.equals(msgType)) {
				logger.info("receiveAndReplyDealerWeChatMsg-text");
				// 将用户提问的内容存入
				// TODO
				int a = insertProblem(content, openId);
				logger.info("保存了" + a + "条记录");
				// 文本类型消息处理
				// 根据内容匹配关键字
				Map<String, Object> result = new HashMap<String, Object>();
				result = keyWords(content, request, response, openId);
				msgType = result.get("replyType").toString();
				xmlMap.put("replyContent", result.get("replyContent").toString() + "\n" + "[0]人工客服");
				logger.info("回复的消息类型为：" + msgType);
				if (WechatDict.MESSAGE_TYPE_TEXT.equals(msgType)) {
					return handleTextMsg(xmlMap);// ,timestamp, nonce
				} else if (WechatDict.MESSAGE_TYPE_NEWS.equals(msgType)) {
					logger.info("receiveAndReplyDealerWeChatMsg-news");
					String fromUserName = xmlMap.get("FromUserName");
					String toUserName = xmlMap.get("ToUserName");
					String event = xmlMap.get("Event");
					// 图文类型消息处理
					return replyImageTextMessage(fromUserName, toUserName, event, result);
				} else {
					return "";
				}

			} else if (WechatDict.MESSAGE_TYPE_VOICE.equals(msgType)) {
				logger.info("receiveAndReplyDealerWeChatMsg-news");
				String fromUserName = xmlMap.get("FromUserName");
				String toUserName = xmlMap.get("ToUserName");
				String event = xmlMap.get("Event");
				Map<String, Object> result = new HashMap<String, Object>();
				// 图文类型消息处理
				return replyImageTextMessage(fromUserName, toUserName, event, result);// ,timestamp,
																						// nonce

			} else if (WechatDict.MESSAGE_TYPE_EVENT.equals(msgType)) {
				logger.info("receiveAndReplyDealerWeChatMsg-event");
				// 事件类型消息处理
				return handleEventMsg(xmlMap, response);// ,dealerAppid,timestamp,
														// nonce

			} else if (WechatDict.MESSAGE_TYPE_IMAGE.equals(msgType)) {

			} else if (WechatDict.MESSAGE_TYPE_VOICE.equals(msgType)) {

			} else if (WechatDict.MESSAGE_TYPE_VOICE.equals(msgType)) {

			}

			return "";
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * @author LiuJun 文本类型消息处理
	 * @date 2016年12月6日
	 * @param msgType
	 * @param map
	 * @return
	 */
	// ,String timestamp, String nonce
	private String handleTextMsg(Map<String, String> msgMap) throws ServiceBizException {
		try {

			// 模拟粉丝发送文本消息给专用测试公众号
			String content = msgMap.get("Content");
			logger.info("handleTextMsg-content=" + content);

			String fromUserName = msgMap.get("FromUserName");
			String toUserName = msgMap.get("ToUserName");

			logger.info("handleTextMsg-fromUserName=" + fromUserName);
			logger.info("handleTextMsg-toUserName=" + toUserName);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ToUserName", fromUserName);
			map.put("FromUserName", toUserName);
			map.put("CreateTime", new Date().getTime() + "");
			map.put("MsgType", WechatDict.MESSAGE_TYPE_TEXT);
			// 模拟粉丝发送文本消息给专用测试公众号，第三方平台方需在5秒内返回空串表明暂时不回复，然后再立即使用客服消息接口发送消息回复粉丝
			if (content.contains("QUERY_AUTH_CODE")) {
				map.put("Content", "");
			} else {// 模拟粉丝发送文本消息给专用测试公众号，第三方平台方需根据文本消息的内容进行相应的响应：
				map.put("Content", msgMap.get("replyContent").toString());
			}

			WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token, WechatDict.AESKey, WechatDict.appid);
			String replyMsg = WechatMessageHandleUtils.mapToXml(map);
			logger.info("handleTextMsg-replyMsg=" + replyMsg);

			// if(content.contains("QUERY_AUTH_CODE")){
			//// new Thread(new Runnable() {
			//// public void run() {
			// try{
			// String[] arr = content.split("\\:");
			// String queryAuthCode = arr[1];
			//
			// logger.info("handleTextMsg-content-QUERY_AUTH_CODE="+queryAuthCode);
			//
			// //获取authorizerAccessToken
			// ApiQueryAuthResult result =
			// wechatInterfaceApiService.queryAuth(queryAuthCode);
			// String authorizerAccessToken =
			// result.getAuthorization_info().getAuthorizer_access_token();
			// logger.info("handleTextMsg-content-authorizerAccessToken="+authorizerAccessToken);
			//
			// CustomerServiceTextMsg textMsg = new CustomerServiceTextMsg();
			// textMsg.setMsgtype(WechatConstant.MESSAGE_TYPE_TEXT);
			// textMsg.setTouser(fromUserName);
			// CustomerServiceTextMsgContent textMsgContent = new
			// CustomerServiceTextMsgContent();
			// textMsgContent.setContent(queryAuthCode+"_from_api");
			// textMsg.setText(textMsgContent);
			// String customerServiceTextMsgJson =
			// SerializeUtils.serialize(textMsg);
			// logger.info("handleTextMsg-customerServiceTextMsgJson="+customerServiceTextMsgJson);
			// wechatInterfaceApiService.replyCustomerServiceTextMsg(authorizerAccessToken,
			// customerServiceTextMsgJson);
			// }catch (Exception e) {
			// logger.error(e.getMessage(),e);
			// }
			//// }
			//// });
			// }
			return replyMsg;
			// return crypt.encryptMsg(replyMsg, timestamp, nonce);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	/**
	 * @author LiuJun 事件类型消息处理
	 * @date 2016年12月8日
	 * @param msgMap
	 * @param timestamp
	 * @param nonce
	 * @return
	 */// ,String dealerAppid,String timestamp, String nonce
	private String handleEventMsg(Map<String, String> msgMap, HttpServletResponse response) {
		logger.info("+++++++++++++++++++++++++++++++++=" + msgMap);
		String event = msgMap.get("Event");
		logger.info("handleEventMsg-event=" + event);
		switch (event) {
		case WechatDict.EVENT_SUBSCRIBE:
			// 用户未关注时，进行关注后的事件推送
			return handleSubscribeEvent(event, msgMap, response);// ,dealerAppid,timestamp,nonce
		case WechatDict.EVENT_SCAN:
			// 用户已关注时的事件推送
			// return null;//
			// handleSubscribeEvent(event,msgMap,dealerAppid,timestamp,nonce);
			return handleSubscribeEvent(event, msgMap, response);
		case WechatDict.EVENT_UNSUBSCRIBE:
			// 用户取消关注时的事件推送
			return handleCancelSubscribeEvent(event, msgMap);// ,dealerAppid,timestamp,nonce

		case WechatDict.EVENT_CLICK:
			// 自定义菜单点击事件
			// return handleClickEvent(msgMap);
			return null;// handleSubscribeEvent(event,msgMap,dealerAppid,timestamp,nonce);
		default:
			return null;// handleSubscribeEvent(event,msgMap,dealerAppid,timestamp,nonce);
		}
	}

	public String getUser(String openid) throws ServiceBizException {
		this.logger.info("getUser,openid=" + openid);
		String url = WechatDict.getOpenInfoUrl;
		url = url.replace("ACCESS_TOKEN", tokenService.getAccessToken());
		url = url.replace("OPENID", openid);
		String body = HttpClientUtil.sendGetRequest(url);
		return body;
	}

	/**
	 * 用户扫描二维码后未关注时点击关注后的事件推送方法
	 * 
	 * @param event
	 * @param msgMap
	 * @param response
	 * @return
	 * @throws ServiceBizException
	 */
	// ,String dealerAppid,String timestamp,String nonce 未关注时的事件推送
	private String handleSubscribeEvent(String event, Map<String, String> msgMap, HttpServletResponse response)
			throws ServiceBizException{
		try {
			String toUserName = msgMap.get("ToUserName");
			String fromUserName = msgMap.get("FromUserName");
			String eventKey = msgMap.get("EventKey");
			String dealerCode = null;
			String phone = null;
			String engine = null;
			String dealer = null;
			String vin = null;
			if (eventKey != null && !"".equals(eventKey)) {
				// 是否存在 vin码
				if (eventKey.indexOf("@") > 0) {
					try {
						String[] strings = eventKey.split("@");
						vin = strings[0].contains("_") ? strings[0].split("_")[1] : strings[0];
						phone = strings[2];
						engine = strings[1];
						dealer = strings[3];
						dealerCode = strings[3];
						logger.info("扫码参数-------------" + vin + phone + dealer + engine);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				} else {
					int i = eventKey.indexOf("qrscene_");
					if (i == 0)
						i = 8;
					dealerCode = eventKey.substring(i, eventKey.length());
					vin = "";
					phone = "";
					engine = "";
					dealer = "";
				}
			}
			String url = WechatDict.getOpenInfoUrl;
			url = url.replace("ACCESS_TOKEN", tokenService.getAccessToken());
			url = url.replace("OPENID", fromUserName);
			String body = HttpClientUtil.sendGetRequest(url);
			JSONObject fromObject = JSONObject.fromObject(body);
			try {
				// 关注后保存用户基本信息
				EventWechatAttentionDTO attentionDto = new EventWechatAttentionDTO();
				attentionDto.setStatus(BusinessConstant.POTENTIAL_USER_STATUS_SUBSCRIBE);
				attentionDto.setSourceType(BusinessConstant.SOURCE_TYPE_WECHAT);
				attentionDto.setNickName(fromObject.get("nickname").toString());
				attentionDto.setHeadImgurl(fromObject.get("headimgurl").toString());
				attentionDto.setCity(fromObject.get("city").toString());
				attentionDto.setCountry(fromObject.get("country").toString());
				attentionDto.setProvince(fromObject.get("province").toString());
				attentionDto.setSex(fromObject.get("sex").toString());
				attentionDto.setSubscribeDate(new Date());
				// attentionDto.setAuthorizerAppid(dealerAppid);
				attentionDto.setOperateType(BusinessConstant.POTENTIALUSER_OPERATETYPE_SUBSCRIBE);
				attentionDto.setDeviceOpenId(fromUserName);
				attentionDto.setCreateDate(new Date());
				attentionDto.setUpdateDate(new Date());
				attentionDto.setDealerCode(dealerCode);
				attentionDto.setVin(vin); // 设置vin码
				attentionDto.setPhone(phone);
				attentionDto.setEngine(engine);
				attentionDto.setDealer(dealer);
				BizEvent et = new BizEvent();
				et.setEventBizType(EventBizType.WECHAT_RELATION);
				et.setEventBizStep(EventBizStep.WECHAT_USER_ATTENTION);
				et.setEventKey("");
				et.setEventData(MapConverUtil.PO2Map(attentionDto)); // 对象转map集合
				eventService.sendEvent2MQ(et); // 调用方法向mq发送消息
				// logger.info("-----user info=" + body);
				logger.info("handleSubscribeEvent-saveOrUpdatePotentialUser is success");

			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			// 关注时回复图文消息dealerAppid,,timestamp,nonce
			// Map<String, Object> result = new HashMap<String, Object>();
			// String replyMsg = replyImageTextMessage(fromUserName, toUserName,
			// event, result);
			//
			// if (!CommonUtils.isNullOrEmpty(replyMsg)) {
			// return replyMsg;
			// } else {
			// // 如果没有图文消息回复
			// // 第三方公众号测试回复,timestamp,nonce
			// return testReplyTextMessage(fromUserName, toUserName, event,
			// response);
			// }
			if (eventKey.indexOf("@") > 0) {
				return saTextMessage(fromUserName, toUserName, event, response);
			}
			return testReplyTextMessage(fromUserName, toUserName, event, response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	/**
	 * 二维码推送信息
	 * 
	 * @param fromUserName
	 * @param toUserName
	 * @param event
	 * @param response
	 * @return
	 * @throws ServiceBizException
	 */
	@SuppressWarnings("unused")
	public String saTextMessage(String fromUserName, String toUserName, String event, HttpServletResponse response)
			throws ServiceBizException{
		try {
			String value = fromUserName;
			String oxid = value + ",," + new Date().toString();
			String openId = CookieSecurityUtil.encrypt(oxid);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ToUserName", fromUserName);
			map.put("FromUserName", toUserName);
			map.put("CreateTime", new Date().getTime() + "");
			map.put("MsgType", WechatDict.MESSAGE_TYPE_TEXT);
			String content = "壮志菱云，共悦人生！欢迎扫码来到菱悦会,感谢您的关注,现诚邀您前往【会·福利】的个人中心进行注册,与广汽三菱一起纵情天地！";
			Map<String, Object> result = ttMessageMapper.findByUserInfo(fromUserName);
			if (result != null) {
				if (!"0".equals(result.get("USER_ID").toString())) {
					if (!"0".equals(result.get("CAR_ID").toString())) {
						content = "欢迎回到菱悦会的大家庭,您已是认证车主!";
					} else {
						content = "";
					}
				}
			}

			map.put("Content", content);
			if (content != null && !"".equals(content)) {
				WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token, WechatDict.AESKey, WechatDict.appid);
				String replyMsg = WechatMessageHandleUtils.mapToXml(map);
				logger.info("handleSubscribeEvent-replyMsg=" + replyMsg);
				return replyMsg;
			}
			// WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token,
			// WechatDict.AESKey, WechatDict.appid);
			// String replyMsg = WechatMessageHandleUtils.mapToXml(map);
			// logger.info ("handleSubscribeEvent-replyMsg=" + replyMsg);
			return "";
			// return crypt.encryptMsg(replyMsg, timestamp, nonce);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	/**
	 * @author LiuJun 第三方公众号测试回复
	 * @date 2016年12月26日
	 * @param fromUserName
	 * @param toUserName
	 * @param event
	 * @param timestamp
	 * @param nonce
	 * @return
	 * @throws ServiceBizException
	 */// ,String timestamp,String nonce
	@SuppressWarnings("unused")
	private String testReplyTextMessage(String fromUserName, String toUserName, String event,
			HttpServletResponse response) throws ServiceBizException {
		try {
			String value = fromUserName;
			String oxid = value + ",," + new Date().toString();
			String openId = CookieSecurityUtil.encrypt(oxid);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ToUserName", fromUserName);
			map.put("FromUserName", toUserName);
			map.put("CreateTime", new Date().getTime() + "");
			map.put("MsgType", WechatDict.MESSAGE_TYPE_TEXT);
			String content = "亲爱的用户，欢迎来到车主一家官方微信服务平台，这里是车主一家唯一官方车友俱乐部。现诚邀您<a href=\"http://carowner.yonyouauto.com/wx/views/modules/register.html?openId="
					+ openId + "\">【点击加入会员】</a>与车主一家一起纵情天地！";

			// String content =
			// "壮志菱云，共悦人生！亲爱的菱粉，欢迎来到广汽三菱官方微信服务平台，这里是广汽三菱唯一官方车友俱乐部——菱悦会，更是以“热爱SUV，创造愉悦生活”为纽带，促进SUV文化交流，实现权益尊享的车主专属互动平台，还有丰富的活动和豪礼相送。现诚邀您<a
			// href=\"http://wxtest.gmmc.com.cn/wx/views/modules/register.html?openId="
			// + openId + "\">【点击加入会员】</a>与广汽三菱一起纵情天地！";
			logger.info("发送的消息体为>>>>>>" + content);
			map.put("Content", content);

			WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token, WechatDict.AESKey, WechatDict.appid);
			String replyMsg = WechatMessageHandleUtils.mapToXml(map);
			logger.info("handleSubscribeEvent-replyMsg=" + replyMsg);
			return replyMsg;
			// return crypt.encryptMsg(replyMsg, timestamp, nonce);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	/**
	 * @author LiuJun 回复图文消息
	 * @date 2016年12月26日
	 * @param authorizerAppid
	 * @param fromUserName
	 * @param toUserName
	 * @param event
	 * @param timestamp
	 * @param nonce
	 * @return
	 * @throws ServiceBizException
	 */// String authorizerAppid,String timestamp,String nonce,
	private String replyImageTextMessage(String fromUserName, String toUserName, String event,
			Map<String, Object> result) throws ServiceBizException {
		try {

			logger.info("replyImageTextMessage is entry");
			// List<NewsActivityDto> dtoList =
			// dealerApiServiceInterface.getTheLastNewsActivityByDealerCode(authorizerAppid);
			List<NewsActivityDto> dtoList = new ArrayList<NewsActivityDto>();
			NewsActivityDto n = new NewsActivityDto();
			n.setTitile(result.get("title").toString());
			n.setTitleImage(result.get("thumb_url").toString());
			n.setContent(result.get("digest").toString());
			n.setContentPath(result.get("url").toString());
			logger.info("存入的值为：" + n);
			dtoList.add(n);
			// if (CommonUtils.isNullOrEmpty(dtoList)) {
			// logger.info("replyImageTextMessage-dtoList is empty");
			// return BusinessConstant.EMPTY_STRING;
			// }
			StringBuffer replyMsg = new StringBuffer("");
			String wechatImageUrl = BusinessConstant.EMPTY_STRING;
			replyMsg.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append("<xml>")
					.append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>")
					.append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>")
					.append("<CreateTime>" + (new Date().getTime()) + "</CreateTime>")
					.append("<MsgType><![CDATA[news]]></MsgType>")
					.append("<ArticleCount>" + dtoList.size() + "</ArticleCount>").append("<Articles>");
			// String titleImage = BusinessConstant.EMPTY_STRING;
			// String newsActivityConntent = BusinessConstant.EMPTY_STRING;
			String subscribeUrl = BusinessConstant.EMPTY_STRING;
			for (NewsActivityDto newsActivityDto : dtoList) {
				// // 如果该字段在发布时没有维护，则重新将该图片发布到微信端并保存url
				// if
				// (CommonUtils.isNullOrEmpty(newsActivityDto.getWechatTitleImageUrl()))
				// {
				// if
				// (CommonUtils.isNullOrEmpty(newsActivityDto.getTitleImage()))
				// {
				// continue;
				// }
				// // wechatImageUrl =
				// wechatInterfaceApiService.getMediaUpLoadingUrl(authorizerAppid,
				// // newsActivityDto.getTitleImage());
				// logger.info("replyImageTextMessage-wechatImageUrl=" +
				// wechatImageUrl);
				// if (CommonUtils.isNullOrEmpty(wechatImageUrl)) {
				// continue;
				// }
				//
				// } else {
				//
				// wechatImageUrl = newsActivityDto.getWechatTitleImageUrl();
				// logger.info("replyImageTextMessage-newsActivityDto.getWechatTitleImageUrl()="
				// + newsActivityDto.getWechatTitleImageUrl());
				//
				// }

				// subscribeUrl =
				// config.getBaseUrl()+"/views/subscribe/subscribeIView.html?naiId="+newsActivityDto.getNaiId();

				replyMsg.append("<item>").append("<Title><![CDATA[" + newsActivityDto.getTitile() + "]]></Title>")
						.append("<Description><![CDATA[" + newsActivityDto.getContent() + "]]></Description>")
						.append("<PicUrl><![CDATA[" + newsActivityDto.getTitleImage() + "]]></PicUrl>")
						.append("<Url><![CDATA[" + newsActivityDto.getContentPath() + "]]></Url>").append("</item>");

			}

			replyMsg.append("</Articles>").append("</xml>");
			logger.info("handleSubscribeEvent-replyImageTextMessage=" + replyMsg.toString());
			return replyMsg.toString();
			// WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token,
			// WechatDict.AESKey, WechatDict.appid);
			// String replyMsg = WechatMessageHandleUtils.mapToXml(map);
			// return crypt.encryptMsg(replyMsg.toString(), timestamp, nonce);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	/**
	 * 用户取消关注时的事件推送
	 * 
	 * @param msgType
	 * @param map
	 * @return
	 * @throws Exception
	 */// ,String dealerAppid,String timestamp,String nonce
	private String handleCancelSubscribeEvent(String event, Map<String, String> msgMap) throws ServiceBizException {
		try {

			String toUserName = msgMap.get("ToUserName");
			String fromUserName = msgMap.get("FromUserName");

			try {

				String openId = msgMap.get("FromUserName");
				EventWechatUnAttentionDTO attentionDto = new EventWechatUnAttentionDTO();
				attentionDto.setStatus(BusinessConstant.POTENTIAL_USER_STATUS_CANCEL);
				attentionDto.setSourceType(BusinessConstant.SOURCE_TYPE_WECHAT);
				// attentionDto.setAuthorizerAppid(dealerAppid);
				attentionDto.setDeviceOpenId(fromUserName);
				attentionDto.setUpdateDate(new Date());
				BizEvent et = new BizEvent();
				et.setEventBizType(EventBizType.WECHAT_RELATION);
				et.setEventBizStep(EventBizStep.WECHAT_USER_UNATTENTION);
				et.setEventData(MapConverUtil.PO2Map(attentionDto));
				eventService.sendEvent2MQ(et);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ToUserName", fromUserName);
			map.put("FromUserName", toUserName);
			map.put("CreateTime", new Date().getTime() + "");
			map.put("MsgType", WechatDict.MESSAGE_TYPE_TEXT);
			map.put("Content", "感谢您的关注！");

			WXBizMsgCrypt crypt = new WXBizMsgCrypt(WechatDict.token, WechatDict.AESKey, WechatDict.appid);
			String replyMsg = WechatMessageHandleUtils.mapToXml(map);
			logger.info("handleCancelSubscribeEvent-replyMsg=" + replyMsg);
			return replyMsg;
			// return crypt.encryptMsg(replyMsg, timestamp, nonce);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	@Transactional
	public String test() throws Exception {
		String result = "";
		try {
			TmPotentialUser record = new TmPotentialUser();
			record.setPotentialUserId(999L);
			record.setDeviceOpenId("sss");
			int i = tmPotentialUserMapper.insertSelective(record);
			logger.info("新增了" + i);
			int a = i / 0;
			logger.info(a);
			return result;
		} catch (Exception e) {
			logger.error("异常：" + e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public JSONObject addMaterialEver(String fileurl, String type) {
		try {
			String token = tokenService.genAccessToken();
			File file = new File(fileurl);
			// 上传素材
			String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type="
					+ type;
			String result = HttpsUtil.connectHttpsByPost(path, null, fileurl); // !!!!!!!!修改处
			result = result.replaceAll("[\\\\]", "");
			System.out.println("result:" + result);
			JSONObject resultJSON = JSONObject.fromObject(result);
			if (resultJSON != null) {
				if (resultJSON.get("media_id") != null) {
					logger.info("上传" + type + "永久素材成功");
					return resultJSON;
				} else {
					logger.info("上传" + type + "永久素材失败");
				}
			}
			return null;
		} catch (IOException e) {
			logger.info("发生异常：" + e.getMessage(), e);
		} catch (NoSuchAlgorithmException e) {
			logger.info("发生异常：" + e.getMessage(), e);
		} catch (NoSuchProviderException e) {
			logger.info("发生异常：" + e.getMessage(), e);
		} catch (KeyManagementException e) {
			logger.info("发生异常：" + e.getMessage(), e);
		}
		return null;
	}

	public Map<String, Object> keyWords(String content, HttpServletRequest req, HttpServletResponse rsp, String openId)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.info("需要匹配的内容为：" + content);
		String oxid = openId + ",," + new Date().toString();
		String OPENID = CookieSecurityUtil.encrypt(oxid);
		String lastKeyWords = "";
		logger.info("关键字样例：" + keyWord);
		// keyWord = new String(keyWord.getBytes("ISO-8859-1"),"UTF-8");
		// logger.info("转码后关键字样例："+keyWord);
		int s = 0;
		String menuInfo = null;
		try {
			lastKeyWords = ttReplyTempMapper.selectKeyId(openId);
			if (CheckUtil.NullOrEmpty(lastKeyWords)) {
				logger.info("没有上一级关键字");
				// 全局搜索关键字
				List<TmReplyKeyword> keyWordList = tmReplyKeywordMapper.selectKeyWords(content);
				if (keyWordList.size() == 0) {
					logger.info("暂未找到该关键字！");
					map.put("resultCode", "1");
					map.put("replyType", "text");
					List<TmReplyKeyword> keyWordLists = tmReplyKeywordMapper.selectKeyWords("?");
					List<TmReplySmart> replyLists = tmReplySmartMapper.selectReplyContent(keyWordLists.get(0).getReplyId().toString());
					map.put("replyContent", replyLists.get(0).getReplyContent());
//					map.put("replyContent", "亲，小友还在成长中，暂时无法理解您的问题，您可以换个问题提问哦~（如输入关键字：" + keyWord + "等与小友聊天。）");
					s = ttReplyTempMapper.deleteReplyTemp(openId);
					logger.info("删除了" + s + "条记录");
				} else {
					if (keyWordList.get(0).getMatchingType() == 1) {
						logger.info("该关键字为全局匹配");
						if (keyWordList.get(0).getKeyword().equals(content)) {
							logger.info("该关键字匹配正确");
							logger.info("该关键字对应的回复有：" + keyWordList.size() + "条");
							// for(TmReplyKeyword keyList : keyWordList){
							Integer replyId = keyWordList.get(0).getReplyId();// 572
							// 根据回复ID去找回复的内容
							logger.info("首次回复ID为：" + replyId);
							List<TmReplySmart> replyList = tmReplySmartMapper.selectReplyContent(replyId.toString());
							if (replyList.size() == 0) {
								logger.info("暂未找到该关键字对应的回复！");
								map.put("resultCode", "1");
								map.put("replyType", "text");
								List<TmReplyKeyword> keyWordLists = tmReplyKeywordMapper.selectKeyWords("?");
								List<TmReplySmart> replyLists = tmReplySmartMapper.selectReplyContent(keyWordLists.get(0).getReplyId().toString());
								map.put("replyContent", replyLists.get(0).getReplyContent());
//								map.put("replyContent",
//										"亲，小友还在成长中，暂时无法理解您的问题，您可以换个问题提问哦~（如输入关键字：" + keyWord + "等与小友聊天。）");
								s = ttReplyTempMapper.deleteReplyTemp(openId);
								logger.info("删除了" + s + "条记录");
							} else {
								logger.info("该关键字对应的回复有：" + replyList.size() + "条");
								menuInfo = tmReplySmartMapper.selectMenuInfo(replyId.toString());
								String menu = "";
								if (menuInfo != null) {
									menu = menu + menuInfo + "\n";
								}
								for (int i = 0; i < replyList.size(); i++) {
									Integer graphicId = replyList.get(i).getGraphicId();
									Integer graphicType = replyList.get(i).getGraphicType();
									Integer replyType = replyList.get(i).getReplyType();
									String replyContent = replyList.get(i).getReplyContent();
									logger.info("处理需要跳转的超链接回复内容");
									if (replyContent.indexOf("href") > 0) {
										logger.info("该回复内容含有超链接，需拼接上openId:" + OPENID);
										replyContent = replyContent.replaceAll("\">", "?openId=" + OPENID + "\">");
										logger.info("该回复内容为：" + replyContent);
									}
									String submenuParentId = replyList.get(i).getSubmenuParentId();
									String submenuSequenceId = replyList.get(i).getSubmenuSequenceId();
									if (WechatDict.REPLY_TYPE_TEXT.equals(replyType.toString())) {
										logger.info("回复类型为：文本");
										map.put("replyType", "text");
										menu = menu + replyContent;
										s = ttReplyTempMapper.deleteReplyTemp(openId);
										logger.info("删除了" + s + "条记录");
									} else if (WechatDict.REPLY_TYPE_NEWS.equals(replyType.toString())) {
										logger.info("回复类型为：图文");
										map.put("replyType", "news");
										s = ttReplyTempMapper.deleteReplyTemp(openId);
										logger.info("删除了" + s + "条记录");
										List<NewsActivityDto> resultList = sendNews(replyList.get(i).getReplyContent());
										for (int l = 0; l < resultList.size(); l++) {
											map.put("title", resultList.get(i).getTitile());
											map.put("thumb_url", resultList.get(i).getTitleImage());
											map.put("digest", resultList.get(i).getContent());
											map.put("url", resultList.get(i).getContentPath());
										}
									} else {
										logger.info("回复类型为：菜单");
										map.put("replyType", "text");
										if (i == replyList.size() - 1) {
											menu = menu + replyList.get(i).getSubmenuSequenceId() + "、" + replyContent;
										} else {
											menu = menu + replyList.get(i).getSubmenuSequenceId() + "、" + replyContent
													+ "\n";
										}
										logger.info("回复的菜单为：" + menu);
										String keyId = ttReplyTempMapper.selectKeyId(openId);
										if (CheckUtil.NullOrEmpty(keyId)) {
											// 新增一条回复记录
											TtReplyTemp record = new TtReplyTemp();
											record.setOpenId(openId);
											record.setReplyId(replyId.toString());
											record.setCreateDate(new Date());
											int a = ttReplyTempMapper.insertSelective(record);
											logger.info("新增了" + a + "条记录");
										} else {
											List<TmReplySmart> child = tmReplySmartMapper
													.selectChilReply(replyList.get(i).getId().toString());
											if (child.size() == 0) {
												s = ttReplyTempMapper.deleteReplyTemp(openId);
												logger.info("删除了" + s + "条记录");
											} else {
												Example example = new Example(TtReplyTemp.class);
												example.createCriteria().andCondition("OPEN_ID=", openId);
												TtReplyTemp record = new TtReplyTemp();
												record.setReplyId(replyId.toString());
												record.setCreateDate(new Date());
												int a = ttReplyTempMapper.updateByExampleSelective(record, example);
												logger.info("更新了" + a + "条");
											}
										}
									}
								}
								logger.info("menu值为：" + menu);
								map.put("resultCode", "0");
								map.put("replyContent", menu);
							}
						} else {
							logger.info("该关键字匹配不正确");
							logger.info("暂未找到该关键字！");
							map.put("resultCode", "1");
							map.put("replyType", "text");
							List<TmReplyKeyword> keyWordLists = tmReplyKeywordMapper.selectKeyWords("?");
							List<TmReplySmart> replyLists = tmReplySmartMapper.selectReplyContent(keyWordLists.get(0).getReplyId().toString());
							map.put("replyContent", replyLists.get(0).getReplyContent());
//							map.put("replyContent", "亲，小友还在成长中，暂时无法理解您的问题，您可以换个问题提问哦~（如输入关键字：" + keyWord + "等与小友聊天。）");
							s = ttReplyTempMapper.deleteReplyTemp(openId);
							logger.info("删除了" + s + "条记录");
						}
					} else {
						logger.info("该关键字为部分匹配");
						logger.info("该关键字对应的回复有：" + keyWordList.size() + "条");
						// for(TmReplyKeyword keyList : keyWordList){
						Integer replyId = keyWordList.get(0).getReplyId();// 661
						// 根据回复ID去找回复的内容
						logger.info("首次回复ID为：" + replyId);
						List<TmReplySmart> replyList = tmReplySmartMapper.selectReplyContent(replyId.toString());
						if (replyList.size() == 0) {
							logger.info("暂未找到该关键字对应的回复！");
							map.put("resultCode", "1");
							map.put("replyType", "text");
							List<TmReplyKeyword> keyWordLists = tmReplyKeywordMapper.selectKeyWords("?");
							List<TmReplySmart> replyLists = tmReplySmartMapper.selectReplyContent(keyWordLists.get(0).getReplyId().toString());
							map.put("replyContent", replyLists.get(0).getReplyContent());
//							map.put("replyContent", "亲，小友还在成长中，暂时无法理解您的问题，您可以换个问题提问哦~（如输入关键字：" + keyWord + "等与小友聊天。）");
							s = ttReplyTempMapper.deleteReplyTemp(openId);
							logger.info("删除了" + s + "条记录");
						} else {
							logger.info("该关键字对应的回复有：" + replyList.size() + "条");
							menuInfo = tmReplySmartMapper.selectMenuInfo(replyId.toString());
							String menu = "";
							if (menuInfo != null) {
								menu = menu + menuInfo + "\n";
							}
							for (int i = 0; i < replyList.size(); i++) {
								Integer graphicId = replyList.get(i).getGraphicId();
								Integer graphicType = replyList.get(i).getGraphicType();
								Integer replyType = replyList.get(i).getReplyType();
								String replyContent = replyList.get(i).getReplyContent();
								logger.info("处理需要跳转的超链接回复内容");
								if (replyContent.indexOf("href") > 0) {
									logger.info("该回复内容含有超链接，需拼接上openId:" + OPENID);
									replyContent = replyContent.replaceAll("\">", "?openId=" + OPENID + "\">");
									logger.info("该回复内容为：" + replyContent);
								}
								String submenuParentId = replyList.get(i).getSubmenuParentId();
								String submenuSequenceId = replyList.get(i).getSubmenuSequenceId();
								if (WechatDict.REPLY_TYPE_TEXT.equals(replyType.toString())) {
									logger.info("回复类型为：文本");
									map.put("replyType", "text");
									menu = menu + replyContent;
									s = ttReplyTempMapper.deleteReplyTemp(openId);
									logger.info("删除了" + s + "条记录");
								} else if (WechatDict.REPLY_TYPE_NEWS.equals(replyType.toString())) {
									logger.info("回复类型为：图文");
									map.put("replyType", "news");
									s = ttReplyTempMapper.deleteReplyTemp(openId);
									logger.info("删除了" + s + "条记录");
									List<NewsActivityDto> resultList = sendNews(replyList.get(i).getReplyContent());
									for (int l = 0; l < resultList.size(); l++) {
										map.put("title", resultList.get(i).getTitile());
										map.put("thumb_url", resultList.get(i).getTitleImage());
										map.put("digest", resultList.get(i).getContent());
										map.put("url", resultList.get(i).getContentPath());
									}
								} else {
									logger.info("回复类型为：菜单");
									map.put("replyType", "text");
									if (i == replyList.size() - 1) {
										menu = menu + replyList.get(i).getSubmenuSequenceId() + "、" + replyContent;
									} else {
										menu = menu + replyList.get(i).getSubmenuSequenceId() + "、" + replyContent
												+ "\n";
									}
									logger.info("回复的菜单为：" + menu);
									String keyId = ttReplyTempMapper.selectKeyId(openId);
									if (CheckUtil.NullOrEmpty(keyId)) {
										// 新增一条回复记录
										TtReplyTemp record = new TtReplyTemp();
										record.setOpenId(openId);
										record.setReplyId(replyId.toString());
										record.setCreateDate(new Date());
										int a = ttReplyTempMapper.insertSelective(record);
										logger.info("新增了" + a + "条记录");
									} else {
										List<TmReplySmart> child = tmReplySmartMapper
												.selectChilReply(replyList.get(i).getId().toString());
//										if (child.size() == 0) {
//											s = ttReplyTempMapper.deleteReplyTemp(openId);
//											logger.info("删除了" + s + "条记录");
//										} else {
											Example example = new Example(TtReplyTemp.class);
											example.createCriteria().andCondition("OPEN_ID=", openId);
											TtReplyTemp record = new TtReplyTemp();
											record.setReplyId(replyId.toString());
											record.setCreateDate(new Date());
											int a = ttReplyTempMapper.updateByExampleSelective(record, example);
											logger.info("更新了" + a + "条");
//										}
									}
								}
							}
							logger.info("menu值为：" + menu);
							map.put("resultCode", "0");
							map.put("replyContent", menu);
						}
					}
				}
			} else {
				logger.info("上一级关键字为：" + lastKeyWords);// 572
				// 在上级关键字的子关键字中匹配关键字（查出用户发送的是之前回复哪一条信息）
				List<TmReplySmart> lastList = tmReplySmartMapper.selectLastContent(lastKeyWords, content);
				if (lastList.size() == 0) {
					logger.info("暂未找到该关键字对应的回复！");
					map.put("resultCode", "1");
					map.put("replyType", "text");
					List<TmReplyKeyword> keyWordLists = tmReplyKeywordMapper.selectKeyWords("?");
					List<TmReplySmart> replyLists = tmReplySmartMapper.selectReplyContent(keyWordLists.get(0).getReplyId().toString());
					map.put("replyContent", replyLists.get(0).getReplyContent());
//					map.put("replyContent", "亲，小友还在成长中，暂时无法理解您的问题，您可以换个问题提问哦~（如输入关键字：" + keyWord + "等与小友聊天。）");
					s = ttReplyTempMapper.deleteReplyTemp(openId);
					logger.info("删除了" + s + "条记录");
				} else {
					Integer replyId = lastList.get(0).getId();
					logger.info("该消息的回复ID为：" + replyId);// 573
					// 根据回复ID去找回复的内容
					List<TmReplySmart> replyList = tmReplySmartMapper.selectReplyContent(replyId.toString());
					if (replyList.size() == 0) {
						logger.info("暂未找到该关键字对应的回复！");
						map.put("resultCode", "1");
						map.put("replyType", "text");
						List<TmReplyKeyword> keyWordLists = tmReplyKeywordMapper.selectKeyWords("?");
						List<TmReplySmart> replyLists = tmReplySmartMapper.selectReplyContent(keyWordLists.get(0).getReplyId().toString());
						map.put("replyContent", replyLists.get(0).getReplyContent());
//						map.put("replyContent", "亲，小友还在成长中，暂时无法理解您的问题，您可以换个问题提问哦~（如输入关键字：" + keyWord + "等与小友聊天。）");
						s = ttReplyTempMapper.deleteReplyTemp(openId);
						logger.info("删除了" + s + "条记录");
					} else {
						logger.info("该关键字对应的回复有：" + replyList.size() + "条");
						menuInfo = tmReplySmartMapper.selectMenuInfo(replyId.toString());
						String menu = "";
						if (menuInfo != null) {
							menu = menu + menuInfo + "\n";
						}
						for (int i = 0; i < replyList.size(); i++) {
							Integer graphicId = replyList.get(i).getGraphicId();
							Integer graphicType = replyList.get(i).getGraphicType();
							Integer replyType = replyList.get(i).getReplyType();
							String replyContent = replyList.get(i).getReplyContent();
							logger.info("处理需要跳转的超链接回复内容");
							if (replyContent.indexOf("href") > 0) {
								logger.info("该回复内容含有超链接，需拼接上openId:" + OPENID);
								replyContent = replyContent.replaceAll("\">", "?openId=" + OPENID + "\">");
								logger.info("该回复内容为：" + replyContent);
							}
							String submenuParentId = replyList.get(i).getSubmenuParentId();
							String submenuSequenceId = replyList.get(i).getSubmenuSequenceId();
							if (WechatDict.REPLY_TYPE_TEXT.equals(replyType.toString())) {
								logger.info("回复类型为：文本");
								map.put("replyType", "text");
								menu = menu + replyContent;
								s = ttReplyTempMapper.deleteReplyTemp(openId);
								logger.info("删除了" + s + "条记录");
							} else if (WechatDict.REPLY_TYPE_NEWS.equals(replyType.toString())) {
								logger.info("回复类型为：图文");
								map.put("replyType", "news");
								s = ttReplyTempMapper.deleteReplyTemp(openId);
								logger.info("删除了" + s + "条记录");
								List<NewsActivityDto> resultList = sendNews(replyList.get(i).getReplyContent());
								for (int l = 0; l < resultList.size(); l++) {
									map.put("title", resultList.get(i).getTitile());
									map.put("thumb_url", resultList.get(i).getTitleImage());
									map.put("digest", resultList.get(i).getContent());
									map.put("url", resultList.get(i).getContentPath());
								}
							} else {
								logger.info("回复类型为：菜单");
								map.put("replyType", "text");
								if (i == replyList.size() - 1) {
									menu = menu + replyList.get(i).getSubmenuSequenceId() + "、" + replyContent;
								} else {
									menu = menu + replyList.get(i).getSubmenuSequenceId() + "、" + replyContent + "\n";
								}
								logger.info("回复的菜单为：" + menu);
								String keyId = ttReplyTempMapper.selectKeyId(openId);
								if (CheckUtil.NullOrEmpty(keyId)) {
									// 新增一条回复记录
									TtReplyTemp record = new TtReplyTemp();
									record.setOpenId(openId);
									record.setReplyId(replyId.toString());
									record.setCreateDate(new Date());
									int a = ttReplyTempMapper.insertSelective(record);
									logger.info("新增了" + a + "条记录");
								} else {
									List<TmReplySmart> child = tmReplySmartMapper
											.selectChilReply(replyList.get(i).getId().toString());
//									if (child.size() == 0) {
//										s = ttReplyTempMapper.deleteReplyTemp(openId);
//										logger.info("删除了" + s + "条记录");
//									} else {
										Example example = new Example(TtReplyTemp.class);
										example.createCriteria().andCondition("OPEN_ID=", openId);
										TtReplyTemp record = new TtReplyTemp();
										record.setReplyId(replyId.toString());
										record.setCreateDate(new Date());
										int a = ttReplyTempMapper.updateByExampleSelective(record, example);
										logger.info("更新了" + a + "条");
//									}
								}
							}
						}
						logger.info("menu的值为：" + menu);
						map.put("resultCode", "0");
						map.put("replyContent", menu);
					}
				}
			}
			// logger.info("返回的Map为：" + map);
			return map;
		} catch (Exception e) {
			s = ttReplyTempMapper.deleteReplyTemp(openId);
			logger.info("删除了" + s + "条记录");
			logger.info("查询发生异常:" + e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public List<NewsActivityDto> sendNews(String mediaId) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<NewsActivityDto> dtoList = new ArrayList<NewsActivityDto>();
		try {
			String ACCESS_TOKEN = tokenService.genAccessToken();
			logger.info("获取到的微信TOKEN为：" + ACCESS_TOKEN);
			String postUrl = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" + ACCESS_TOKEN;
			String jsonBody = "{\"media_id\":\"" + mediaId + "\"}";
			logger.info("jsonBody>>>>" + jsonBody);
			String result = FrameHttpUtil.post(postUrl, jsonBody);
			logger.info("开始解析返回值");
			JSONObject jsonObject = JSONObject.fromObject(result);
			logger.info("解析result!");
			JSONArray newsItem = JSONArray.fromObject(jsonObject.getString("news_item"));
			logger.info("解析返回值成功");
			for (int i = 0; i < newsItem.size(); i++) {
				String title = newsItem.getJSONObject(i).getString("title");
				logger.info("title>>>>>>>>>" + title);
				String thumb_url = newsItem.getJSONObject(i).getString("thumb_url");
				logger.info("thumb_url>>>>>>>>>" + thumb_url);
				String digest = newsItem.getJSONObject(i).getString("digest");
				logger.info("digest>>>>>>>>>" + digest);
				String content = newsItem.getJSONObject(i).getString("content");
				logger.info("content>>>>>>>>>" + content);
				String url = newsItem.getJSONObject(i).getString("url");
				logger.info("url>>>>>>>>>" + url);
				resultMap.put("title", title);
				resultMap.put("thumb_url", thumb_url);
				resultMap.put("content", content);
				resultMap.put("digest", digest);
				resultMap.put("url", url);
				NewsActivityDto n = new NewsActivityDto();
				n.setTitile(title);
				n.setTitleImage(thumb_url);
				n.setContent(digest);
				n.setContentPath(url);
				dtoList.add(n);
			}
			// logger.info("返回的MAP为："+resultMap);
			return dtoList;
		} catch (Exception e) {
			logger.info("查询发生异常:" + e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 发送保险到期的通知
	 * 
	 * @author Administrator
	 * @date 2017年7月26日
	 * @return
	 */
	public WeChatMessageProtocol sendInsuranceExpire(String openId) {
		WeChatMessageProtocol messageProtocol = new WeChatMessageProtocol();

		WeChatMessageProtocolReceiver receiver = new WeChatMessageProtocolReceiver();
		receiver.setDetail(true);
		receiver.setPlatform(MessagePushConstant.PUSH_PLATFORM.WC_PUBLIC);
		receiver.addDetailList(openId);

		WeChatMessageProtocolMessageContent message = new WeChatMessageProtocolMessageContent();
		// 积分变动
		message.setContent("TM00619");

		message.setSourceType(BusinessConstant.SOURCE_TYPE_WECHAT);

		WeChatMessageProtocolMessageTemplateContent content1 = new WeChatMessageProtocolMessageTemplateContent();
		content1.setKey("first");
		content1.setValue("您的保险即将到期");
		content1.addExtraMap(WX_MSG_PROP_COLOR, "#FF0000");
		message.addTemplateConentList(content1);

		WeChatMessageProtocolMessageTemplateContent content2 = new WeChatMessageProtocolMessageTemplateContent();
		content2.setKey("keynote1");
		content2.setValue("2017-07-08");
		message.addTemplateConentList(content2);

		WeChatMessageProtocolMessageTemplateContent content3 = new WeChatMessageProtocolMessageTemplateContent();
		content3.setKey("keynote2");
		content3.setValue(DateUtil.formateDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
		message.addTemplateConentList(content3);

		WeChatMessageProtocolMessageTemplateContent content4 = new WeChatMessageProtocolMessageTemplateContent();
		content4.setKey("remark");
		content4.setValue("请及时处理哦!");
		message.addTemplateConentList(content4);

		WeChatMessageProtocolSender sender = new WeChatMessageProtocolSender();
		sender.setOriginApplicationHost("host1");
		sender.setOriginApplicationName("app1");
		sender.setClientAppId("wxb85ed633e428bafc");
		sender.setDealerCode("00000");
		messageProtocol.setMessage(message);
		messageProtocol.setReceiver(receiver);
		messageProtocol.setSender(sender);
		messageProtocol.setPushChannel(MessagePushConstant.PUSH_CHANNEL.WEBCHAT);

		return messageProtocol;
	}

	public int insertProblem(String content, String openId) throws Exception {
		int s = 0;
		TtUserProblem ttUserProblem = new TtUserProblem();
		try {
			ttUserProblem.setMessageContent(content);
			ttUserProblem.setOpenId(openId);
			ttUserProblem.setCreateDate(new Date());
			s = ttUserProblemMapper.insertSelective(ttUserProblem);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return s;
	}

	/**
	 * 客服回复用户消息
	 * 
	 * @author Administrator
	 * @date 2017年12月22日
	 * @param wxGzMessageDto
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> replyMsgToUser(WxGzMessageDto wxGzMessageDto, String token) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			logger.info("token为：" + token);
			String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token;
			logger.info("url为：" + url);
			String msgType = wxGzMessageDto.getMsgType();
			String openId = wxGzMessageDto.getToUserName();
			Map<String, Object> msgMap = new HashMap<String, Object>();
			Map<String, Object> map = new HashMap<String, Object>();
			msgMap.put("touser", wxGzMessageDto.getToUserName());
			msgMap.put("msgtype", msgType);
			if (msgType.equals(WechatDict.MESSAGE_TYPE_TEXT)) {
				logger.info("发送文本消息");
				map.put("content", wxGzMessageDto.getContent());
				msgMap.put(WechatDict.MESSAGE_TYPE_TEXT, map);
			} else if (msgType.equals(WechatDict.MESSAGE_TYPE_IMAGE)) {
				logger.info("发送图片消息");
				map.put("media_id", wxGzMessageDto.getMediaId());
				msgMap.put(WechatDict.MESSAGE_TYPE_IMAGE, map);
			} else if (msgType.equals(WechatDict.MESSAGE_TYPE_VOICE)) {
				logger.info("发送语音消息");
				map.put("media_id", wxGzMessageDto.getMediaId());
				msgMap.put(WechatDict.MESSAGE_TYPE_VOICE, map);
			} else if (msgType.equals(WechatDict.MESSAGE_TYPE_VIDEO)) {
				logger.info("发送视频消息");
				map.put("media_id", wxGzMessageDto.getMediaId());
				map.put("thumb_media_id", wxGzMessageDto.getThumbMediaId());
				map.put("title", wxGzMessageDto.getTitle());
				map.put("description", wxGzMessageDto.getDescription());
				msgMap.put(WechatDict.MESSAGE_TYPE_VIDEO, map);
			} else if (msgType.equals(WechatDict.MESSAGE_TYPE_MUSIC)) {
				logger.info("发送音乐消息");
				map.put("title", wxGzMessageDto.getTitle());
				map.put("description", wxGzMessageDto.getDescription());
				map.put("musicurl", wxGzMessageDto.getMusicurl());
				map.put("hqmusicurl", wxGzMessageDto.getHqmusicurl());
				map.put("thumb_media_id", wxGzMessageDto.getThumbMediaId());
				msgMap.put(WechatDict.MESSAGE_TYPE_MUSIC, map);
			} else if (msgType.equals(WechatDict.MESSAGE_TYPE_NEWS)) {
				logger.info("发送图文消息（点击跳转到外链）");
				// map.put("content", wxGzMessageDto.getContent());
				// msgMap.put(WechatDict.MESSAGE_TYPE_NEWS, map);
				// TODO 暂时处理成与跳转到图文消息页面一致
				map.put("media_id", wxGzMessageDto.getMediaId());
				msgMap.put(WechatDict.MESSAGE_TYPE_MPNEWS, map);
			} else if (msgType.equals(WechatDict.MESSAGE_TYPE_MPNEWS)) {
				logger.info("发送图文消息（点击跳转到图文消息页面）");
				map.put("media_id", wxGzMessageDto.getMediaId());
				msgMap.put(WechatDict.MESSAGE_TYPE_MPNEWS, map);
			} else {
				logger.info("无法识别的消息类型");
				result.put("errorCode", "500");
				result.put("errorMsg", "无法识别的消息类型");
				return result;
			}
			JSONObject jsonObject = JSONObject.fromObject(msgMap);
			String resultMsg = FrameHttpUtil.post(url, jsonObject.toString());
			JSONObject jsons = JSONObject.fromObject(resultMsg);
			if (jsons == null || jsons.isNullObject()) {
				logger.info("返回结果为空");
				result.put("errorCode", "500");
				result.put("errorMsg", "调用微信接口异常");
				return result;
			} else {
				String errcode = jsons.getString("errcode");
				if (errcode.equals("0")) {
					logger.info("回复消息成功！");
					result.put("errorCode", "200");
					result.put("errorMsg", "回复成功！");
					Example example = new Example(TmPotentialUser.class);
					example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
					TmPotentialUser record = new TmPotentialUser();
					record.setIfCustomerService((short) 0);
					record.setServiceTime(new Date());
					tmPotentialUserMapper.updateByExampleSelective(record, example);
				} else {
					String errmsg = jsons.getString("errmsg");
					logger.info("回复消息异常!");
					result.put("errorCode", errcode);
					result.put("errorMsg", errmsg);
					return result;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	public String receiveMsg(String xml, HttpServletResponse response, HttpServletRequest request)
			throws ServiceBizException {
		Map<String, String> xmlMap = WechatMessageHandleUtils.xmlToMap(xml);// parsedXml
		String returnMsg = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ToUserName", xmlMap.get("FromUserName"));
			map.put("FromUserName", xmlMap.get("ToUserName"));
			map.put("CreateTime", new Date().getTime() + "");
			map.put("MsgType", WechatDict.MESSAGE_TYPE_TEXT);
			map.put("Content", "网络服务异常，请您稍后再试！");
			returnMsg = WechatMessageHandleUtils.mapToXml(map);

			String openId = request.getHeader(ApiVersionConsts.HEADER_OPENID);
			String msgType = xmlMap.get("MsgType");
			String content = xmlMap.get("Content");
			String msgId = xmlMap.get("MsgId");
			WxGzMessageDto wxgzMsg = new WxGzMessageDto();
			if (WechatDict.MESSAGE_TYPE_TEXT.equals(msgType)) {
				wxgzMsg.setContent(xmlMap.get("Content"));
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
			} else if (WechatDict.MESSAGE_TYPE_IMAGE.equals(msgType)) {
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
				wxgzMsg.setPicUrl(xmlMap.get("PicUrl"));
				wxgzMsg.setMediaId(xmlMap.get("MediaId"));
			} else if (WechatDict.MESSAGE_TYPE_EVENT.equals(msgType)) {
				logger.info("receiveAndReplyDealerWeChatMsg-event");
				// 事件类型消息处理
				return handleEventMsg(xmlMap, response);
			} else if (WechatDict.MESSAGE_TYPE_VOICE.equals(msgType)) {
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
				wxgzMsg.setFormat(xmlMap.get("Format"));
				wxgzMsg.setMediaId(xmlMap.get("MediaId"));
				wxgzMsg.setRecognition(xmlMap.get("Recognition"));
			} else if (WechatDict.MESSAGE_TYPE_VIDEO.equals(msgType)) {
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
				wxgzMsg.setMediaId(xmlMap.get("MediaId"));
				wxgzMsg.setThumbMediaId(xmlMap.get("ThumbMediaId"));
			} else if (WechatDict.MESSAGE_TYPE_SHORTVIDEO.equals(msgType)) {
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
				wxgzMsg.setMediaId(xmlMap.get("MediaId"));
				wxgzMsg.setThumbMediaId(xmlMap.get("ThumbMediaId"));
			} else if (WechatDict.MESSAGE_TYPE_LOCATION.equals(msgType)) {
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
				wxgzMsg.setScale(xmlMap.get("Scale"));
				wxgzMsg.setLabel(xmlMap.get("Label"));
				wxgzMsg.setLocation_X(xmlMap.get("Location_X"));
				wxgzMsg.setLocation_Y(xmlMap.get("Location_Y"));
			} else if (WechatDict.MESSAGE_TYPE_LINK.equals(msgType)) {
				wxgzMsg.setMsgID(xmlMap.get("MsgId"));
				wxgzMsg.setMsgType(xmlMap.get("MsgType"));
				wxgzMsg.setCreateTime(xmlMap.get("CreateTime"));
				wxgzMsg.setFromUserName(xmlMap.get("FromUserName"));
				wxgzMsg.setTitle(xmlMap.get("Title"));
				wxgzMsg.setDescription(xmlMap.get("Description"));
				wxgzMsg.setUrl(xmlMap.get("Url"));
			} else {
				return "";
			}
			logger.info("消息参数为：" + wxgzMsg);
			Result<String> result = chatServiceInterface.getWxgzMsg(wxgzMsg);
			logger.info("返回结果：" + result);
			Integer code = result.getReturnFlag();
			map.put("MsgType", WechatDict.MESSAGE_TYPE_TEXT);
			if (code.equals(ApiVersionConsts.CUSTOMER_IN_LINE)) {
				map.put("Content", "客服忙碌，请等待，正在排队中...");
				returnMsg = WechatMessageHandleUtils.mapToXml(map);
			} else if (code.equals(ApiVersionConsts.CUSTOMER_BUSY)) {
				map.put("Content", "客服忙碌，请稍后再试。");
				returnMsg = WechatMessageHandleUtils.mapToXml(map);
			} else if (code.equals(ApiVersionConsts.CUSTOMER_OFFLINE)) {
				map.put("Content", "目前没有在线状态的客服。");
				returnMsg = WechatMessageHandleUtils.mapToXml(map);
			} else if (code.equals(ApiVersionConsts.CUSTOMER_NOT_FREE)) {
				map.put("Content", "目前没有空闲的在线客服。");
				returnMsg = WechatMessageHandleUtils.mapToXml(map);
			} else if (code.equals(ApiVersionConsts.MEDIA_FILE_OVERFLOW)) {
				map.put("Content", "媒体消息文件超过2MB。");
				returnMsg = WechatMessageHandleUtils.mapToXml(map);
			} else if (code.equals(ApiVersionConsts.SEND_MESSAGE_FILE)) {
				map.put("Content", "消息发送失败。");
				returnMsg = WechatMessageHandleUtils.mapToXml(map);
			} else {
				returnMsg = "";
			}
			logger.info(result);
			Example example = new Example(TmPotentialUser.class);
			example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
			TmPotentialUser record = new TmPotentialUser();
			record.setIfCustomerService((short) 0);
			record.setServiceTime(new Date());
			tmPotentialUserMapper.updateByExampleSelective(record, example);
			return returnMsg;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return returnMsg;
		}
	}

	/**
	 * 判断是否需要客服
	 * 
	 * @author Administrator
	 * @date 2017年12月27日
	 * @param xml
	 * @return
	 */
	public int confirmService(String xml) {
		Map<String, String> xmlMap = WechatMessageHandleUtils.xmlToMap(xml);
		String content = xmlMap.get("Content");
		String openId = xmlMap.get("FromUserName");
		Example example = new Example(TmPotentialUser.class);
		example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
		List<TmPotentialUser> list = tmPotentialUserMapper.selectByExample(example);
		if (list.size() == 0) {
			logger.info("查无此人");
			return 1;
		} else {
			if (CheckUtil.NullOrEmpty(list.get(0).getIfCustomerService())) {
				if (content.equals("0")) {
					TmPotentialUser record = new TmPotentialUser();
					record.setIfCustomerService((short) 0);
					record.setServiceTime(new Date());
					int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
					if (a == 0) {
						logger.info("转接客服失败");
						return 3;
					} else {
						logger.info("正在转接客服");
						return 2;
					}
				}
				logger.info("该用户没有选择人工客服功能");
				return 1;
			} else {
				if (list.get(0).getIfCustomerService() == 1) {
					if (content.equals("0")) {
						TmPotentialUser record = new TmPotentialUser();
						record.setIfCustomerService((short) 0);
						record.setServiceTime(new Date());
						int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
						if (a == 0) {
							logger.info("转接客服失败");
							return 3;
						} else {
							logger.info("正在转接客服");
							return 2;
						}
					}
					logger.info("该用户没有选择人工客服功能");
					return 1;
				} else {
					Date serviceTime = list.get(0).getServiceTime();
					Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
					ca.setTime(serviceTime); // 设置时间为当前时间
					ca.add(Calendar.MINUTE, 5);
					if (ca.getTime().getTime() >= new Date().getTime()) {
						logger.info("该用户处于客服有效时间内");
						return 0;
					} else {
						if (content.equals("0")) {
							TmPotentialUser record = new TmPotentialUser();
							record.setIfCustomerService((short) 0);
							record.setServiceTime(new Date());
							int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
							if (a == 0) {
								logger.info("转接客服失败");
								return 3;
							} else {
								logger.info("正在转接客服");
								return 2;
							}
						}
						return 1;
					}
				}
			}
		}
	}

	/**
	 * 断开微信用户与客服的连接
	 * 
	 * @author Administrator
	 * @date 2018年1月22日
	 * @param openId
	 * @return
	 */
	public Map<String, Object> disconnect(String openId) {
		Map<String, Object> result = new HashMap<String, Object>();
		Example example = new Example(TmPotentialUser.class);
		example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
		List<TmPotentialUser> list = tmPotentialUserMapper.selectByExample(example);
		if (list.size() != 0) {
			TmPotentialUser record = new TmPotentialUser();
			record.setIfCustomerService((short) 1);
			record.setServiceTime(new Date());
			int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
			if (a == 1) {
				logger.info("成功断开客服连接");
				result.put("errorCode", "200");
				result.put("errorMsg", "成功断开客服连接");
			} else {
				logger.info("断开客服连接异常");
				result.put("errorCode", "500");
				result.put("errorMsg", "断开客服连接异常");
			}
		} else {
			logger.info("该OpenId不存在");
			result.put("errorCode", "500");
			result.put("errorMsg", "该OpenId不存在");
		}
		return result;
	}

	public String selectUserIdByOpenId(String openId) {
		String userId = "";
		userId = tmPotentialUserMapper.selectUserIdByOpenId(openId);
		return userId;
	}
}
